define(function () {
    'use strict';

    function ctrl($scope, $filter, $ionicScrollDelegate, $stateParams, $timeout, InfoService,$ionicLoading,CommonService) {

        $scope.vm = {};
        $scope.channel = {};

        $scope.$on('$ionicView.beforeEnter', function() {
            init();
        });

        $scope.doRefresh = function() {
            init().finally(function(){
                $scope.$broadcast('scroll.refreshComplete');
            });
        };

        $scope.$watch("vm.activeTab", function(newValue, oldValue){
            if(newValue) {
                $timeout(function(){
                    $ionicScrollDelegate.resize();
                }, 500);
            }
        });

        function init(){
            if(!$scope.channels){
                $ionicLoading.show();
            }
            $scope.channel.channelId = $stateParams['id'];

            return InfoService.getChannelInfosByParentId($scope.channel.channelId).then(function(data){
                $scope.channels = data;
                for(var i = 0; i < $scope.channels.length; i++) {
                    var channel = $scope.channels[i];
                    if(i == 0) {
                        $scope.vm.activeTab=channel.id;
                    }
                    (function(c){
                        InfoService.getProductsByChannelId(c.id).then(
                            function(products) {
                                c.products =  products;
                                for(var i=0;i<c.products.length;i++){
                                    var fund = c.products[i];
                                    fund.prod_min_subscribe = $filter('prodMinSubscribe')(CommonService.getMinAmount(fund));
                                }
                            }
                        )
                    })(channel);
                    $ionicLoading.hide();
                }
            });
        }
    }

    ctrl.$inject = ['$scope','$filter','$ionicScrollDelegate','$stateParams','$timeout', 'InfoService','$ionicLoading','CommonService'];
    return ctrl;
});